﻿using RinNote.Server.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RinNote.Server.Authentication
{
    /// <summary>
    /// 用户验证相关
    /// </summary>
    class UserAuthorization
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="expiryDate"></param>
        /// <returns></returns>
        public static string UserLogin(string username, string password, DateTime expiryDate)
        {
            using (RinNoteContext entity = new RinNoteContext())
            {
                var user = entity.account.Where(i => i.UserName == username && i.Password == password).FirstOrDefault();
                if (user != null)
                {
                    return UserMapper.GenerateToken(user, expiryDate);
                }
            }
            return null;
        }
        /// <summary>
        /// 用户登出
        /// </summary>
        /// <param name="nancyContext"></param>
        public static void UserLogout(Nancy.NancyContext nancyContext)
        {
            string token = GetToken(nancyContext);
            UserMapper.RemoveToken(token);
        }
        /// <summary>
        /// 根据Token获得用户信息
        /// </summary>
        /// <returns></returns>
        public static Account GetUserByToken(Nancy.NancyContext nancyContext)
        {
            string token = GetToken(nancyContext);
            return UserMapper.GetUserAccountFromAccessToken(token);
        }
        /// <summary>
        /// 获得Token
        /// </summary>
        /// <param name="nancyContext"></param>
        /// <returns></returns>
        public static string GetToken(Nancy.NancyContext nancyContext)
        {
            string token = nancyContext.Request.Headers.Authorization;
            return token;
        }
    }
}
